<?

	require_once '_uniquedir.php';

	class Fmgr0v0r01_Thumbs extends Fmgr0v0r01__uniquedir{
	
		protected $rdk = 'temp';
		protected $mod = 775;
		
		protected $valid_child_classnames = 'thumb,htaccess';
		
		protected $htcontent = "Order Deny,Allow\nDeny From All\n\n<FilesMatch \"\.(gif|jpe?g|png|GIF|JPE?G|PNG)$\">\t\nAllow From All\n</FilesMatch>\n";
		
		protected $thumbs;
		
		protected function read_permissions(){
			parent::read_permissions();
			if(!file_exists($this->realpath('.htaccess'))){
				$this->mkfil('.htaccess', array('contents'=>$this->htcontent));								
			}				
		}
		
		function thumb($file){
			return $this->mkthumb($file);
		}
		
		function has_thumb($file){
			if(!$this->pkg->is_fmgr_image($file)) return false;
			return is_dir($this->realpath($file->id));
		}
	
		private function thumb_obj($file){
			if(!$this->has_thumb($file)) return false;
			if(!isset($this->thumbs[$file->id])) $this->thumbs[$file->id] = $this->child($file->id);
			return $this->thumbs[$file->id];
		}
	
		private function mkthumb($file){
			if(!$this->pkg->is_fmgr_image($file) || !$file->is_readable()) return false;
			if($file->rdk() == 'temp') return false;
			if(!$thumb = $this->thumb_obj($file)){
				$thumb = $this->mkdir($file->id);
				$this->cleanup_on_shutdown();
			}
			return $thumb;
		}
		
		function cleanup(){
			$al = $this->pkg->al();
			$tb = $this->table();
			foreach($this->contents(1) as $id){
				if($al->exists($tb, array('id'=>$id))) continue;
				$fp = $this->realpath($id);
				foreach(HostInterface::dir_contents($fp) as $f) @unlink($this->realpath("$id/$f"));
				@rmdir($fp);
				if($c = $this->child($id)) $child->destroy();
			}
		}
		
		function cleanup_on_shutdown(){
			smuoi_register_shutdown_function(array($this, 'cleanup'));
		}
				
		function unthumb($file){
			if(!$thumb = $this->thumb_obj($file)) return true;
			if(!$thumb->destroy()) return false;
			unset($this->thumbs[$file->id]);
			return true;
		}

	}

?>